package app.controllers.member;

import app.Const;
import app.constant.MemberConstant;
import app.constant.OrderConstant;
import app.constant.TransferConstant;
import app.dtos.ProductBizDto;
import app.kit.TypeKit;
import app.models.basic.Dict;
import app.models.member.Member;
import app.models.member.MemberProduct;
import app.models.transfer.TransferProduct;
import app.models.transfer.TransferRule;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.jfinal.plugin.activerecord.Page;
import goja.StringPool;
import goja.mvc.Controller;
import goja.plugins.sqlinxml.SqlKit;
import goja.security.goja.SecurityKit;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.Days;

import java.math.BigDecimal;
import java.util.List;

import static app.Const.FIELD_COLLECTION_MODE;
import static app.constant.MemberConstant.DEFAULT_STATUS;
import static app.constant.MemberConstant.PLAYMONEY_NO;
import static app.constant.MemberConstant.PLAYMONEY_OK;
import static app.constant.MemberConstant.PLAYMONEY_SUBMIT;
import static app.constant.MemberConstant.PRODUCT_EXPIRE;
import static app.constant.MemberConstant.PRODUCT_FOUND;
import static app.constant.MemberConstant.PRODUCT_HOLDING;
import static app.constant.MemberConstant.PRODUCT_SALE;
import static app.constant.MemberConstant.PRODUCT_SALES_SUCCESS;
import static app.constant.MemberConstant.PRODUCT_SALE_FAIL;
import static app.constant.MemberConstant.REDEEM_AUDIT;
import static app.constant.MemberConstant.REDEEM_SUCCESS;
import static app.constant.MemberConstant.TRANSFER_AUDIT_SUCCESS;
import static app.constant.MemberConstant.TRANSFER_TRADE_FAIL;
import static app.constant.MemberConstant.TRANSFER_TRADE_SUCCESS;
import static app.models.member.MemberProduct.FIELD_PRODUCT_STATUS;
import static app.models.member.MemberProduct.dao;


/**
 * <p>
 *  我的理财
 * </p>
 *
 * @author liuhui
 * @version 1.0
 * @since JDK 1.6
 */
public class ProductController extends Controller {


    /**
     * 默认页面
     * 查询持有中
     */
    public void index(){
        Member member = SecurityKit.getLoginUser(getRequest());
        int mid = member.getId();

        int page = getParaToInt("page", 1);
        int pageSize = getParaToInt("pageSize", Const.PAGE);

        StringBuilder whereSql = new StringBuilder();

        List<Object> params = Lists.newArrayList();
        params.add(mid);

        String orderno = getPara("orderno");
        if (!Strings.isNullOrEmpty(orderno)) {
            whereSql.append(" AND o.trade_no = ?");
            params.add(orderno);
        }
        int status = getParaToInt("ps", 0);
        if (status > 0) {
            switch (status) {
                case 1:
                    //退单申请中
                    whereSql.append(" AND mp.redeem_status =? ");
                    params.add(REDEEM_AUDIT);
                    break;
                case 2:
                    //已退单
                    whereSql.append(" AND mp.redeem_status =? ");
                    params.add(REDEEM_SUCCESS);
                    break;
                case 3:
                    //可转让

                    break;
                case 4:
                    //转让中
                    whereSql.append(" AND mp.transfer_status =? ");
                    params.add(TRANSFER_AUDIT_SUCCESS);
                    break;
                case 5:
                    // 已转让
                    whereSql.append(" AND mp.transfer_status =? ");
                    params.add(TRANSFER_TRADE_SUCCESS);
                    break;

            }
        }

        int moneyStatus = getParaToInt("ms", 0);
        if(moneyStatus > 0){
            switch (moneyStatus){
                case 1:
                    whereSql.append(" AND mp.playmoney_status in (?,?) ");
                    params.add(PLAYMONEY_NO);
                    params.add(PLAYMONEY_SUBMIT);
                    break;
                case 2:
                    //已打款
                    whereSql.append(" AND mp.playmoney_status = ?");
                    params.add(PLAYMONEY_OK);
                    break;
            }
        }
        if(moneyStatus == DEFAULT_STATUS && status == DEFAULT_STATUS){

            String default_where = " AND mp.product_status IN (?, ?, ?, ?, ?) AND mp.redeem_status !=? AND mp.transfer_status != ?";
            params.add(PRODUCT_SALE);
            params.add(PRODUCT_SALES_SUCCESS);
            params.add(PRODUCT_SALE_FAIL);
            params.add(PRODUCT_HOLDING);
            params.add(PRODUCT_FOUND);

            params.add(REDEEM_SUCCESS);

            params.add(TRANSFER_TRADE_SUCCESS);
            whereSql.append(default_where);
        }


        Page<MemberProduct> paginate = dao.paginate(page, pageSize,
                SqlKit.sql("memberproduct.front_select"),
                String.format(SqlKit.sql("memberproduct.front_hode_where"), whereSql),
                params.toArray());
        setAttr("data", paginate);
        setAttr("orderno", orderno);
        setAttr("ps", status);
        setAttr("ms", moneyStatus);
    }

    /**
     * 产品详情
     */
    public void detail() {
        final int id = getParaToInt(0, 0);
        if (id <= 0) {
            renderError(404);
        } else {
            Member loginUser = SecurityKit.getLoginUser(getRequest());
            MemberProduct memberProduct = dao.findDetailById(id, loginUser.getId());
            if (memberProduct == null) {
                redirect("/member/product");
                return;
            }
            setAttr("product", memberProduct);
            // 计算显示
            int productStatus = TypeKit.getInt(memberProduct, FIELD_PRODUCT_STATUS);
            String productStatusTxt;
            switch (productStatus) {
                case MemberConstant.PRODUCT_SALE:
                case MemberConstant.PRODUCT_SALES_SUCCESS:
                    productStatusTxt = "认购中";
                    break;
                case MemberConstant.PRODUCT_EXPIRE:
                    productStatusTxt = "已结束";
                    break;
                case MemberConstant.PRODUCT_FOUND:
                    productStatusTxt = "认购成功";
                    break;
                case MemberConstant.PRODUCT_SALE_FAIL:
                    productStatusTxt = "认购失败";
                    break;
                default:
                    productStatusTxt = "认购成功";
                    break;
            }
            setAttr("productStatus", productStatusTxt);

            String order_type = memberProduct.getStr("order_type");
            String orderTypeTxt ;
            if(StringUtils.equals(order_type, OrderConstant.BUY_TYPE)){
                orderTypeTxt = "投资订单";
            } else if (StringUtils.equals(order_type, OrderConstant.TFR_TYPE)){
                orderTypeTxt = "转让订单";
            } else {
                orderTypeTxt = "普通订单";
            }
            setAttr("orderType", orderTypeTxt);

            setAttr(FIELD_COLLECTION_MODE, Dict.dao.collection_mode_map(TypeKit.getInt(memberProduct,FIELD_COLLECTION_MODE)));

            DateTime end_date = TypeKit.getDateTime(memberProduct, "end_date");
            int days;
            if (end_date == null) {
                days = 0;
            } else {
                days = Days.daysBetween(DateTime.now(), end_date).getDays();
                if (days == 0) days = 1;
            }
            setAttr("days", days >= 0 ? days : 0);

            // 计算预期收益

            BigDecimal prifit = memberProduct.profit();
            setAttr("prifit",prifit);

            // 检查状态
            ProductBizDto bizDto = memberProduct.bizStatus();
            setAttr("bizbtn", bizDto);

            int transferStatus = TypeKit.getInt(memberProduct, MemberProduct.FIELD_TRANSFER_STATUS);
            TransferProduct transferProduct = null;
            switch (transferStatus){
                case TRANSFER_AUDIT_SUCCESS:
                    transferProduct = TransferProduct.dao.findByMemberProductDetail(id, TransferConstant.STATUE_TRADING);
                    break;
                case TRANSFER_TRADE_SUCCESS:
                    transferProduct = TransferProduct.dao.findByMemberProductDetail(id, TransferConstant.STATUE_SUCCESS);
                    break;
                case TRANSFER_TRADE_FAIL:
                    transferProduct = TransferProduct.dao.findByMemberProductDetail(id, TransferConstant.STATUE_FAIL);
                    break;
                default:
//                    transferProduct = TransferProduct.dao.findByMemberProductDetail(id, TransferConstant.STATUE_CANCEL);
                    break;
            }
            if(transferProduct != null){
                DateTime put_time = TypeKit.getDateTime(transferProduct, "put_time");
                if(put_time != null){
                    DateTime trade_time = TypeKit.getDateTime(transferProduct,"trade_time");
                    int lodging_hours = TypeKit.getInt(transferProduct,"lodging_hours");
                    TransferRule rule = TransferRule.dao.findDefault();
                    setAttr("transfer_rule", rule);
                    setAttr("put_time", put_time.toDate());
                    setAttr("put_days", trade_time !=null ? (lodging_hours+1) : Days.daysBetween(put_time, DateTime.now()).getDays() + 1);
                    setAttr("transferproduct", transferProduct);
                }
            }

        }
    }


    /**
     * 已结束
     */
    public void over(){
        Member member = SecurityKit.getLoginUser(getRequest());
        int mid = member.getNumber(StringPool.PK_COLUMN).intValue();

        int page = getParaToInt("page", 1);
        int pageSize = getParaToInt("pageSize", Const.PAGE);
        Page<MemberProduct> paginate = dao.paginate(page, pageSize,
                SqlKit.sql("memberproduct.front_select"),
                SqlKit.sql("memberproduct.front_over_where"), mid,PRODUCT_EXPIRE, TRANSFER_TRADE_SUCCESS,REDEEM_SUCCESS);
        setAttr("data",paginate);
    }

}
